<?php

namespace app\admin\controller\finance;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Wages extends Backend
{
    
    /**
     * Wages模型对象
     * @var \app\admin\model\Wages
     */
    protected $model = null;
    protected $searchFields = 'username,shenfenzheng';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wages;
        $this->Wageslist = new \app\admin\model\Wageslist;
        $this->view->assign("yanfaList", $this->model->getYanfaList());

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['wageslist'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['wageslist'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('wageslist')->visible(['user_id','shenfenzheng','base_pay','hfbt','jtbt','yxygbt','glbt','ylbx','yilbx','sybx','zfgjj','feixiao']);
            }
            $list = collection($list)->toArray();
            //获取搜索值
            $search = str_replace('{}','',$this->request->request('filter'));

            if($search){
                $searchList = json_decode('['.$search.']',true);
                Session::set("searchList", $searchList);
            }else{

                Session::set("list",$list);

            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    //获取部门信息
    public function department(){
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
        }
    }
    /**
     * 勾选推送消息
     */
    public function send($ids = "")
    {
        if ($ids) {
            $data = Db::name('wages')->alias('a')

                ->join('wageslist b','a.shenfenzheng = b.shenfenzheng')

                ->whereIn('a.id',$ids)

                ->select();


        }else{
            //读取页面搜索数据，默认进列表为初始数据
            $searchList = Session::get('searchList')[0];

            if($searchList){

                $data = Db::name('wages')->alias('a')

                    ->join('wageslist b','a.shenfenzheng = b.shenfenzheng')

                    ->where($searchList)

                    ->select();
            }else{
                $data = Session::get('list');

            }

        }

        if($data){
            foreach ($data as $v){

                if(!empty($v['wageslist'])){
                    $v['user_id'] = $v['wageslist']['user_id'];
                }
                pushMsgText(Admin::UserConfig(),'text',['content'=>123123],$v['user_id'],1);
                Session::delete("list");
            }
        }else{
            $this->error("暂无推送队列");
        }
    }
//    //推送消息
//    public function send(){
//        //查询页面展示数据
//        $wages_info = $this->index();
//        var_dump($wages_info);exit;
//        pushMsgText(Admin::UserConfig(),'12321321','WuJinJun01',1);
//    }
    //导入结算工资
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        $sum = 0;

        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            //去除空格圆角符号
            $row['shenfenzheng'] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","",$row['shenfenzheng']);
            //查询用户基本工资信息
            $user_info = $this->Wageslist->where('shenfenzheng',$row['shenfenzheng'])->field('user_id,base_pay,hfbt,jtbt,yxygbt,glbt,ylbx,yilbx,sybx,zfgjj,feixiao')->find();
            //应发工资
            $row['yingfagongzi'] = Rounding(($user_info['base_pay']+$user_info['hfbt']+$user_info['jtbt']+$user_info['yxygbt']+$user_info['glbt']+$row['canbu']+$row['qitabutie'])-$row['koukuan']);

            //个人应纳税所得额
            $jiaoshuijine =  Rounding($row['yingfagongzi']-$user_info['ylbx']-$user_info['yilbx']-$user_info['sybx']-$user_info['zfgjj']);
            //个人所得税
            if($jiaoshuijine <= 3000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.03);
            }elseif($jiaoshuijine >3000 && $jiaoshuijine <=12000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.1-210);
            }elseif($jiaoshuijine >12000 && $jiaoshuijine <=25000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.2-1410);
            }elseif($jiaoshuijine >25000 && $jiaoshuijine <=35000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.25-2660);
            }elseif($jiaoshuijine >35000 && $jiaoshuijine <=55000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.3-4410);
            }elseif($jiaoshuijine >55000 && $jiaoshuijine <=80000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.35-7160);
            }elseif($jiaoshuijine >80000){
                $row['suodeshui'] = Rounding($jiaoshuijine*0.45-15160);
            }
            //$where = "datemonth = '".$row['year']."' and userid='".$user_info['user_id']."'";


            $bukou = Db::table('hdyj_finance_extract_month')
                ->where('datemonth','eq',$row['year'])
                ->where('userid',$user_info['user_id'])
                ->field('owe_tax,repair_tax')
                ->find();
            //补扣多扣税额
            $row['bukoushuier'] =Rounding($bukou['repair_tax'] - $bukou['owe_tax']);
            //实发工资
            $row['shifagongzi'] = Rounding($jiaoshuijine-$row['suodeshui'] + $row['bukoushuier']);
            //绩效版税小计
            $row['jixiaobanshuixiaoji'] = Rounding($row['jiabanbanshui']+$row['jixiaobanshui']);
            //应发合计
            $row['yingfaheji'] = Rounding($row['yingfagongzi']+$row['jixiaobanshuixiaoji']-$row['koufa']);
            //部门应发工资总计
            $sum += Rounding($row['yingfagongzi']);
            //非销方式定义
            $row['feixiao'] = $user_info['feixiao'];

            if ($row) {
                $insert[] = $row;
            }
        }

        foreach ($insert as $ks=>$vs){
            //按提成算
            if($vs['feixiao']==0){
                $insert[$ks]['feixiaobanshui'] = Rounding($vs['yingfagongzi']/$sum*$vs['zongticheng']);
            }else{
                //按套结算
                $insert[$ks]['feixiaobanshui'] = Rounding($vs['xiaoshoutaoshu']*$vs['feixiao']);
            }
            //版税合计
            $insert[$ks]['banshuiheji'] = Rounding($vs['jixiaobanshuixiaoji']+$insert[$ks]['feixiaobanshui']);
            //应发版税
            $insert[$ks]['yingfabanshui'] = Rounding($insert[$ks]['banshuiheji']-$vs['koufa']);
            //版税实发
            $insert[$ks]['banshuishifa'] = Rounding($insert[$ks]['yingfabanshui']-$vs['banshuishuijin']);
            unset($insert[$ks]['feixiao']);
        }

        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->group('department')
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : ''
                ];
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
